package com.tuling.controller;


import com.tuling.entity.Result;
import com.tuling.entity.User;
import com.tuling.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/***
 * @author : fujc-dev@qq.com
 * @motto : talk is cheap, show me the code. salute the future!
 */
@Controller
@ResponseBody
@Api("用户接口")
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    MessageSource messageSource;


    //Rest  /user/1
    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "无", required = true)
    //用处不大
    //@ApiResponse(message = "返回的公共Result对象，会封装User对象", response = Result.class, code = 200)
    public Result getUser(@PathVariable Integer id) {
        //int a = 1 / 0;
        //LocaleContextHolder 就是一个Locale持有器  springmvc底层会自动将LocalResovler中语言设置进去
        String message = messageSource.getMessage("user.query.success", null, LocaleContextHolder.getLocale());

        User user = userService.getUserById(id);
        return new Result<>(200, message, user);
    }

    // 新增 /user/add
    @PostMapping("/add")
    @ApiOperation("添加用户")
    @ApiImplicitParam(name = "user", value = "User实体json", defaultValue = "无", required = true)
    public Result addUser(@RequestBody User user) {

        System.out.println(user);
        userService.add(user);
        return new Result<>(200, "添加成功", userService.getAllUser());
    }

    // 修改 /user1
    @PutMapping("/{id}")
    @ApiOperation("编辑用户")
    public Result editUser(@RequestBody User user) {
        userService.update(user);
        return new Result<>(200, "修改成功", userService.getAllUser());
    }

    // 删除 /user1
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @CrossOrigin("http://localhost:8081")
    public Result deleteUser(@PathVariable Integer id) {
        userService.delete(id);
        return new Result<>(200, "删除成功", userService.getAllUser());
    }

}
